<?php
/*
* LoginController.php
* Handles the flow of the login.
*/
class LoginController
{
	/** StartController.
	* Controlls the flow of the user login.
	*/
	public function doController()
	{
		// The return string
		$xhtml = '';
	
		// Requires LoginView.
		require_once 'LoginView.php';
		$loginView = new LoginView();
		
		// Requires LoginModel.
		require_once 'LoginModel.php';
		$loginModel = new LoginModel( $this->databaseConnection );
		
		// If the user isn't logged in
		if ( $loginView->IsLoggedIn() == false)
		{
			// Show the login form.
			$xhtml .= $loginView->doLoginForm();
			
			// Has the user tried to login
			if ( $loginView->triedToLogin() == true )
			{
				// Check the credentials, Login the user.
				if ( $loginModel->LoginUser( $loginView->GetPostUsername(), $loginView->GetPostPassword() ) == true )
				{	
					$xhtml = 'Logged in. ';
					$xhtml .= $loginView->doLogOutButton();
					
					// Checks if the user tried to Logout.
					if ( $loginView->triedToLogout() == true )
					{
						// Logout the user.
						$loginView->Logout();
					}
				}
				// Invalid username and/or password.
				else
				{
					$xhtml .= 'Invalid username and/or password.';
				}
			}
		}
		// User already logged in.
		else 
		{
			$xhtml .= 'Already logged in';
			$xhtml .= $loginView->doLogOutButton();
			
			// Checks if the user tried to Logout.
			if ( $loginView->triedToLogout() == true )
			{
				// Logout the user.
				$loginView->Logout();
			}
		}
		
		// Returs the returnstring.
		return $xhtml;
	}
}